<?php

namespace Apps\AppApi\Method\Question;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Enum\SearchDataType;
use Apps\Common\Libs\Keyword;
use Apps\Common\Libs\SearchASync;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\Question;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\CosQKeyword;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Libs\Jpush;


/**
 * 添加问题
 * @package Apps\AppApi\Method\Question
 */
class Add extends BaseMethod
{
    /**
     * @var \Apps\Common\Models\Question
     */
    private $success = 0;
    private $id = 0;

    public function run()
    {
    	/**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }

        $question_tag = $this->getDataItem('tag', '');
        $custom_tag = $this->getDataItem('custom_tag', '');
        $question_content = Keyword::Filter($this->getDataItem('content',''));
        $city_code = (string)$this->getDataItem('city_code', '0');

        $up = new UploadPic();
        if ($question_pics = $up->questionPic()) {
//            $question_pics = json_encode(array_slice($question_pics, 0, 3));
            $question_pics = json_encode($question_pics);
        } else {
            $question_pics = json_encode([]);
        }

        if(!empty($question_content) && $city_code != '0') {
            $q = new Question();
            $q->user_id = $this->getUserAuth()->userId;

            //关键字替换
            $keyword = CosQKeyword::query() -> execute() -> toArray();
            foreach ($keyword as $k => $v){
            	 
            	$question_content = str_replace($v['keyword'], '***', $question_content);
                   
            }
            $tagList = [];
            if ($question_tag) {
                $tag_id = '';
                foreach ($question_tag as $k => $val) {
                    $tagList[] = $val['name'];
                    $tag_id .= $val['id'] . ',';
                }
                $tagLists = BeautyParlorTagInfo::query()->where('tag_id in(' . trim($tag_id, ',') . ')')->execute()->toArray();
                foreach ($tagLists as $val) {
                    if ($val['parent_id'] == 0) {
                        return $this->errorLog(ResultStatus::POST_BODY_FORMAT_ERROR, '不能选择一级标签！');
                    }
                }
            }
            if ($custom_tag) {
                $tagList[] = $custom_tag;
            }
            if ($tagList) {
                $q->question_tag = json_encode($tagList);
            }
            // 过滤表情
            $q->question_content = preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return ''; }, $question_content);
            //$q->question_content = $question_content;
//            $q->question_content = preg_replace('/[\xf0-\xf7].{3}/', '', $question_content);
            /*if (preg_match('/[\xf0-\xf7].{3}/', $question_content)) {
                return $this->errorLog(ResultStatus::POST_BODY_FORMAT_ERROR, "不能发布特殊字符");
            }*/
//            $q->question_content = $question_content;
            $q->question_pics = $question_pics;
            $date = date('Y-m-d H:i:s');
            $q->last_reply_time = $date;
            $q->question_addtime = $date;
//            $q->city_code = $city_code;
            $q->city_code = 0;

            if($q->save()){
                if ($question_tag) { // 保存问答的标签
                    $tagData = '';
                    foreach ($question_tag as $k => $val) {
                        $tagData .= "({$val['id']}, '{$val["name"]}', {$q->question_id}),";
                    }
                    $tagData = trim($tagData, ',');
                    $q->getReadConnection()->query("INSERT INTO question_tag (tag_id, tag_name, question_id) VALUES {$tagData}");
                }
                $this->id = $q->question_id;
                $this->success = 1;
//                SearchASync::Instance()->noticeSync($q->question_id, SearchDataType::Question);
                //推送消息
                $phoneNum = [
                	'15823522906',
                	'13883156314',
                	'18725873971',
                	'15086691064',
                	'18996156384',
                	'13752904126',
                	'18523066564',
                	'15723278358',
                	'18523989994',
                	'15111992368',
                	'18123640250',
                    '18323868684',

                    '18008393331', // 5月4号新加
                ];

                /* // 推送测试（测试用的）
                $phoneNum = [
                    '18723568681',
                    '17790274639',
                    '18225097233',
                    '18723793180'
                ]; */
                $push = new Jpush();
                foreach($phoneNum as $k => $v){
                    $param = array(
                        'type' => 8,
                        'ispushservice' => 0,
                        'phone' => $v, 
                        'message_link_type' => 'question',
			            'message_link_data' => $this->id,
                        'content' => '有新的问题啦:'.mb_substr($q->question_content,0,10,'utf-8').'，快去回答吧！',
                        'shop_id' => 0
                    );

                    $rs = $push -> setval($param);
                    if(empty($rs)){
                        $push -> push();
                    }
                    continue;
                }
                
            } else {
            	
                return $this->databaseErrorLog($q);
            }
        } else {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "");
        }

        $this->setResult([
            'id' => $this->id,
            'success' => $this->success
        ]);
    }

}